﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using WaterCloud.Code;
using SqlSugar;
using WaterCloud.DataBase;
using WaterCloud.Domain.SalaryManagement;
using WaterCloud.Domain.AttendanceManagement;
using WaterCloud.Domain.SystemOrganize;
using WaterCloud.Domain.ContractManagement;
using WaterCloud.Domain.WelfaresubsidyManagement;
using WaterCloud.Domain.SocialSecurityManagement;
using WaterCloud.Domain.PerformanceManagement;
using Org.BouncyCastle.Asn1.Cms;
using WaterCloud.Service.SocialSecurityManagement;
using static iTextSharp.text.pdf.AcroFields;

namespace WaterCloud.Service.SalaryManagement
{
    /// <summary>
    /// 创 建：超级管理员
    /// 日 期：2025-04-24 10:21
    /// 描 述：工资核算表服务类
    /// </summary>
    public class SalarytableService : BaseService<SalarytableEntity>, IDenpendency
    {
        public BigsickitemsService _bigsickservice { get; set; }
        public SalarytableService(ISqlSugarClient context) : base(context)
        {
        }
        #region 获取数据
        public async Task<List<SalarytableEntity>> GetList(string keyword = "")
        {
            var data = repository.IQueryable();
            if (!string.IsNullOrEmpty(keyword))
            {
                data = data.Where(a => a.F_EnCode.Contains(keyword)
                || a.F_FullName.Contains(keyword));
            }
            return await data.Where(a => a.F_DeleteMark == false).OrderBy(a => a.F_Id, OrderByType.Desc).ToListAsync();
        }
        public async Task<List<SalarytableitemsEntity>> ExportForm(string keyword = "")
        {

            var data = await Db.Queryable<SalarytableitemsEntity>().Where(a => a.F_HeadId == keyword)
            .ToListAsync();

            return data;

        }
        public async Task<List<SalarytableEntity>> GetLookList(string keyword = "")
        {
            var query = repository.IQueryable().Where(a => a.F_DeleteMark == false);
            if (!string.IsNullOrEmpty(keyword))
            {
                //此处需修改
                query = query.Where(a => a.F_EnCode.Contains(keyword)
                || a.F_FullName.Contains(keyword));
            }
            //权限过滤
            query = GetDataPrivilege("a", "", query);
            return await query.OrderBy(a => a.F_Id, OrderByType.Desc).ToListAsync();
        }

        public async Task<List<SalarytableEntity>> GetLookList(SoulPage<SalarytableEntity> pagination, string keyword = "", string id = "")
        {
            var query = repository.IQueryable().Where(a => a.F_DeleteMark == false);
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(a => a.F_EnCode.Contains(keyword)
                || a.F_FullName.Contains(keyword));
            }
            if (!string.IsNullOrEmpty(id))
            {
                query = query.Where(a => a.F_Id == id);
            }
            //权限过滤
            query = GetDataPrivilege("a", "", query);
            return await query.ToPageListAsync(pagination);
        }

        public async Task<SalarytableEntity> GetForm(string keyValue)
        {
            var data = await repository.FindEntity(keyValue);
            data.list = await repository.Db.Queryable<SalarytableitemsEntity>().Where(a => a.F_HeadId == keyValue).ToListAsync();
            return data;
        }
        #endregion

        public async Task<SalarytableEntity> GetLookForm(string keyValue)
        {
            var data = await repository.FindEntity(keyValue);
            data.list = await repository.Db.Queryable<SalarytableitemsEntity>().Where(a => a.F_HeadId == keyValue).ToListAsync();
            return GetFieldsFilterData(data);
        }
        public List<SalarytableitemsEntity> CalculateWages(string keyword = "", string id = "")
        {    //转化为日期格式
            var time = Convert.ToDateTime(keyword + "-01");
            //查询工厂日历，满勤天数
            float? faccalendar = 0;
            var faccalendardata = Db.Queryable<FactorycalendarEntity>().Where(a => SqlFunc.DateDiff(DateType.Month, Convert.ToDateTime(a.F_DateTime), time) == 0).ToList();
            if (faccalendardata.Count > 0)
            {
                faccalendar = faccalendardata[0].F_Days;
            }
            // 查询薪资参数
            var param = Db.Queryable<SalaryparameterEntity>().ToList()[0];
            //查询所有在职人员的薪资方案
            var user = Db.Queryable<UserEntity, PersonsalaryEntity, BasicsalaryEntity, JobsalaryEntity, SkillssalaryEntity, WorkagesalaryEntity, BenefitsalaryEntity, PerformancesalaryEntity, DaysalaryEntity>(
                (a, b, c, d, e, f, g, h, i) => new JoinQueryInfos(
             JoinType.Left, a.F_Id == b.F_UserId,

             JoinType.Left, b.F_BasicSalaryNum == c.F_EnCode,
             JoinType.Left, b.F_JopSalaryNum == d.F_EnCode,
              JoinType.Left, b.F_SkillsSalaryNum == e.F_EnCode,
               JoinType.Left, b.F_WorkAgeSalaryNum == f.F_EnCode,
                JoinType.Left, b.F_BenefitSalaryNum == g.F_EnCode,
             JoinType.Left, b.F_PerformanceSalaryNum == h.F_EnCode,
             JoinType.Left, b.F_DaySalaryNum == i.F_EnCode
             ))
             .Where(a => a.F_WorkState == 1 || a.F_WorkState == 0)
                .Select((a, b, c, d, e, f, g, h, i) => new
                {
                    UserId = a.F_Id,
                    RealName = a.F_RealName,
                    UserNum = a.F_Num,
                    orgid = a.F_OrganizeId,
                    SalaryType = b.F_SalaryTypeNum,
                    BasicAmount = c.F_Amount,

                    BasicAttendance = c.F_Attendance,
                    BasicTolerance = c.F_Tolerance,

                    JopAmount = d.F_Amount,
                    JopAttendance = d.F_Attendance,
                    JopTolerance = d.F_Tolerance,
                    JopName = d.F_FullName,
                    SkillsAmount = e.F_Amount,
                    SkillsAttendance = e.F_Attendance,
                    SkillsTolerance = e.F_Tolerance,
                    WorkageAmount = f.F_Amount,
                    WorkageMaxYears = f.F_MaxYears,
                    WorkageAttendance = f.F_Attendance,
                    WorkageTolerance = f.F_Tolerance,
                    BenefitCoefficient = g.F_Coefficient,
                    BenefitAttendance = g.F_Attendance,
                    BenefitTolerance = g.F_Tolerance,
                    PerAmount = h.F_Amount,
                    PerAttendance = g.F_Attendance,
                    WelfareSubsidy = b.F_WelfareSubsidyNum,
                    PerTolerance = g.F_Tolerance,
                    DayAmount = i.F_Amount,
                    ComAge = SqlFunc.DateDiff(DateType.Year, Convert.ToDateTime(a.F_Redate), DateTime.Now),
                }).MergeTable().ToList();

            List<SalarytableitemsEntity> salarytableitemsList = new List<SalarytableitemsEntity>();

            foreach (var item in user)
            {
                SalarytableitemsEntity salary = new SalarytableitemsEntity();

                //请假天数计算
                var holidays = repository.Db.Queryable<HolidayEntity, HolidaytypeEntity>((a, b) => new JoinQueryInfos(
            JoinType.Left, a.F_HolidayTypeId == b.F_Id
            ))
                .GroupBy(a => a.F_HolidayTypeId)
                .Where((a) => SqlFunc.DateDiff(DateType.Month, Convert.ToDateTime(a.F_StartDate)
                , time) == 0
                && a.F_UserNum == item.UserNum && a.F_EnabledMark == true)

              .Select((a, b) => new HolidaytypeEntity()
              {

                  F_Id = a.F_HolidayTypeId,
                  F_Days = SqlFunc.AggregateSum(a.F_Days)

              }).ToList();
                //查询出勤天数
                //float? days = 0;
                //if (holidays.Count > 0)
                //{
                //   days = faccalendar - (float)Convert.ToDouble(holidays[0].F_Days);
                //}
                //else
                //{
                //    days =faccalendar;
                //}
                //   var days = repository.Db.Queryable<AttendancetableitemsEntity, AttendancetableEntity>((a, b) => new JoinQueryInfos(
                //JoinType.Left, a.F_HeadId == b.F_Id
                //)).GroupBy(a => new { a.F_Datetime })
                //.Where((a, b) => SqlFunc.DateDiff(DateType.Month, Convert.ToDateTime(b.F_HeadDate), time) == 0 && a.F_UserNum == item.UserNum)

                // .Select((a, b) => new AttendancetableitemsEntity
                // {
                //     F_Datetime = a.F_Datetime,
                // }).MergeTable().Count();





                //查询班次
                var shiftnum = repository.Db.Queryable<AttendancetableitemsEntity, AttendancetableEntity>((a, b) => new JoinQueryInfos(
             JoinType.Left, a.F_HeadId == b.F_Id
             )).GroupBy(a => new { a.F_Shift })
             .Where((a, b) => SqlFunc.DateDiff(DateType.Month, Convert.ToDateTime(b.F_HeadDate), time) == 0 && a.F_UserNum == item.UserNum)

              .Select((a, b) => new
              {
                  shift = a.F_Shift,
                  shiftcount = SqlFunc.AggregateCount(a.F_Shift),


              }).MergeTable().ToList();

                //汇总工时和加班数据

                var hours = repository.Db.Queryable<AttendancetableitemsEntity, AttendancetableEntity>((a, b) => new JoinQueryInfos(
             JoinType.Left, a.F_HeadId == b.F_Id
             )).GroupBy(a => new { a.F_UserNum })
             .Where((a, b) => SqlFunc.DateDiff(DateType.Month, Convert.ToDateTime(b.F_HeadDate), time) == 0 && a.F_UserNum == item.UserNum && a.F_EnabledMark == true)

              .Select((a, b) => new AttendancetableitemsEntity
              {

                  F_Times1 = SqlFunc.AggregateSum(a.F_Times1),//工时
                  F_Times2 = SqlFunc.AggregateSum(a.F_Times2),//加班
                  F_Times3 = SqlFunc.AggregateSum(a.F_Times3),//六日
                  F_Times4 = SqlFunc.AggregateSum(a.F_Times4),//法定假日
                  F_SubsidyAmount = SqlFunc.AggregateSum(a.F_SubsidyAmount),//工序补贴金额

              }).MergeTable().ToList();

                float? days = 0;
                if (hours.Count > 0)
                {
                    days = hours[0].F_Times1 / 8;
                }

                //计算日结工资
                if (item.SalaryType == "2")
                {
                    if (days > 0)
                    {

                        salary.F_ReallySalary = days * item.DayAmount;

                    }
                }
                else
                {


                    //计算基本工资
                    if (days > 0)
                    {
                        if (item.SalaryType == "0") //计时工资
                        {
                            salary.F_BasicSalary = item.BasicAmount;
                            if (item.BasicAttendance == true)
                            {

                                if (holidays.Count() > 0)
                                {
                                    var temp = Hoildaysum(holidays, item.BasicAmount, faccalendar, (bool)item.BasicTolerance);
                                    salary.F_BasicSalary = item.BasicAmount / faccalendar * days + temp;
                                    salary.F_HolidaySalary = salary.F_HolidaySalary + temp;
                                }
                            }


                        }
                        else
                        {
                            salary.F_BasicSalary = 0;
                        }
                    }
                    else
                    {
                        salary.F_BasicSalary = 0;

                    }

                    //计算岗位工资
                    if (days > 0)
                    {
                        salary.F_JopSalary = item.JopAmount;
                        if (item.JopAttendance == true)
                        {

                            if (holidays.Count() > 0)
                            {
                                var temp = Hoildaysum(holidays, item.JopAmount, faccalendar, (bool)item.JopTolerance);
                                salary.F_JopSalary = item.JopAmount / faccalendar * days + temp;
                                salary.F_HolidaySalary = salary.F_HolidaySalary + temp;
                            }

                        }
                    }
                    else
                    {
                        salary.F_JopSalary = 0;
                    }
                    //计算技能工资
                    if (days > 0)
                    {
                        salary.F_SkillsSalary = item.SkillsAmount;
                        if (item.SkillsAttendance == true)
                        {

                            if (holidays.Count() > 0)
                            {
                                var temp = Hoildaysum(holidays, item.SkillsAmount, faccalendar, (bool)item.SkillsTolerance);
                                salary.F_SkillsSalary = item.SkillsAmount / faccalendar * days + temp;
                                salary.F_HolidaySalary = salary.F_HolidaySalary + temp;
                            }

                        }
                    }
                    else
                    {
                        salary.F_SkillsSalary = 0;
                    }

                    //计算司龄工资
                    if (days > 0)
                    {
                        if (item.ComAge <= param.F_MaxYears)
                        {
                            salary.F_ComAgeSalary = item.ComAge * item.WorkageAmount;
                        }
                        else
                        {
                            salary.F_ComAgeSalary = param.F_MaxYears * item.WorkageAmount;
                        }
                        if (item.WorkageAttendance == true)
                        {
                            if (holidays.Count() > 0)
                            {
                                var temp = Hoildaysum(holidays, salary.F_ComAgeSalary, faccalendar, (bool)item.WorkageTolerance);

                                salary.F_ComAgeSalary = salary.F_ComAgeSalary / faccalendar * days + temp;
                                salary.F_HolidaySalary = salary.F_HolidaySalary + temp;
                            }

                        }
                    }
                    else
                    {
                        salary.F_ComAgeSalary = 0;
                    }

                    //绩效工资 F_PerformanceSalary



                    //占位符

                    //效益工资
                    var bene = Db.Queryable<BenefitsalarytableEntity>()
                         .Where(a => SqlFunc.DateDiff(DateType.Month, Convert.ToDateTime(a.F_DateTime), time) == 0)
                         .Select(a => new { Amount = a.F_Amount })
                         .ToList();

                    if (days > 0)
                    {
                        if (item.SalaryType == "0") //计时工资
                        {
                            if (bene.Count > 0)
                            {
                                salary.F_BenefitSalary = bene[0].Amount * item.BenefitCoefficient;
                            }
                        }
                        else
                        {
                            if (hours.Count > 0)
                            {
                                salary.F_BenefitSalary = item.BasicAmount / faccalendar * hours[0].F_Times1;
                            }
                            else
                            {
                                salary.F_BenefitSalary = 0;
                            }

                        }
                        if (item.BenefitAttendance == true)
                        {
                            if (holidays.Count() > 0)
                            {
                                var temp = Hoildaysum(holidays, salary.F_BenefitSalary, faccalendar, (bool)item.BenefitTolerance);

                                salary.F_BenefitSalary = salary.F_BenefitSalary / faccalendar * days + temp;
                                salary.F_HolidaySalary = salary.F_HolidaySalary + temp;
                            }
                        }



                    }
                    else
                    {
                        salary.F_BenefitSalary = 0;
                    }

                    //计算加班工资
                    if (hours.Count > 0)
                    {
                        var Times2 = item.BasicAmount / faccalendar * hours[0].F_Times2 * param.F_Overtime1;
                        var Times3 = item.BasicAmount / faccalendar * hours[0].F_Times3 * param.F_Overtime2;
                        var Times4 = item.BasicAmount / faccalendar * hours[0].F_Times4 * param.F_Overtime3;
                        salary.F_TimesSalary = Times2 + Times3 + Times4;
                        salary.F_Times2 = hours[0].F_Times2;//加班
                        salary.F_Times3 = hours[0].F_Times3;//六日加班
                        salary.F_Times4 = hours[0].F_Times4;//法定假日
                        salary.F_SubsidyAmount = hours[0].F_SubsidyAmount; //工序补贴
                    }
                    else
                    {
                        salary.F_Times2 = 0;
                        salary.F_Times3 = 0;
                        salary.F_Times4 = 0;
                        salary.F_TimesSalary = 0;
                        salary.F_SubsidyAmount = 0;
                    }
                    //计算班次补助
                    float? shiftsalary = 0;
                    if (shiftnum.Count > 0)
                    {
                        foreach (var shiftitem in shiftnum)
                        {
                            var subsidy = Db.Queryable<ShiftEntity>().Where(a => a.F_EnCode == shiftitem.shift)
                                .Select(a => a.F_Subsidy).ToList()[0];

                            shiftsalary = shiftsalary + (subsidy * shiftitem.shiftcount);

                        }
                        salary.F_NightShiftSalary = shiftsalary;
                    }
                    else
                    {
                        salary.F_NightShiftSalary = 0;
                    }


                    //计算福利补贴
                    float? subsidysalary = 0;
                    float? subsidysalary1 = 0;
                    var subsidylitem = "";
                    if (days > 0)
                    {
                        if (item.WelfareSubsidy != null)
                        {
                            var wlist = item.WelfareSubsidy.Split(',').ToList();
                            foreach (var w in wlist)
                            {
                                var subsidy = Db.Queryable<WelfaresubsidyitemsEntity>().Where(a => a.F_EnCode == w)
                                    .Select(a => new
                                    {
                                        Fullname = a.F_FullName, //项目
                                        Attendance = a.F_Attendance, //是否考勤相关
                                        Tolerance = a.F_Tolerance, //是否考勤容差
                                        Cycle = a.F_Cycle,   //周期
                                        Amount = a.F_Amount,//福利金额
                                    }).ToList();
                                if (subsidy.Count > 0)
                                {

                                    var m = Convert.ToDateTime(keyword).Month;
                                    var cycle = subsidy[0].Cycle.Split(',');
                                    if (cycle.Length > 0)
                                    {
                                        if (cycle.Contains(m.ToString()))
                                        {
                                            if (subsidy[0].Attendance == true)
                                            { //是否考勤相关
                                                var temp = Hoildaysum(holidays, subsidy[0].Amount, faccalendar, (bool)subsidy[0].Attendance);

                                                subsidysalary1 = subsidy[0].Amount / faccalendar * days + temp; ;
                                                subsidysalary = subsidysalary + subsidysalary1;
                                                salary.F_HolidaySalary = salary.F_HolidaySalary + temp;

                                            }
                                            else
                                            {
                                                subsidysalary1 = subsidy[0].Amount;
                                                subsidysalary = subsidysalary + subsidysalary1;
                                            }
                                            subsidylitem = subsidylitem + subsidy[0].Fullname + ":" + subsidysalary1 + ",";
                                        }
                                    }


                                }

                            }
                            salary.F_WelfareSubsidy = subsidylitem;
                            salary.F_WelfareSubsidySalary = subsidysalary;
                        }
                    }
                    else
                    {
                        salary.F_WelfareSubsidy = "";
                        salary.F_WelfareSubsidySalary = 0;

                    }
                    //计算五险一金
                    var insuranceitems = "";
                    float? insurancesalary = 0;
                    float? insurancesalary1 = 0;


                    var insurance = Db.Queryable<InsuranceEntity>().Where(a => a.F_UserNum == item.UserNum)
                      .Select(a => new
                      {
                          Amount = a.F_Amount,//社保基数
                          Amount1 = a.F_Amount1,//公积金基数
                          InsuranceItems = a.F_InsuranceItems,//五险
                          Providentitems = a.F_ProvidentItems //公积金
                      }).ToList();

                    //五险
                    if (insurance.Count > 0)
                    {
                        if (insurance[0].InsuranceItems.Count() > 0)
                        {
                            var insuranceItems = insurance[0].InsuranceItems.Split(",").ToList();


                            foreach (var insuranceItem in insuranceItems)
                            {
                                var insu = Db.Queryable<InsuranceitemsEntity>().Where(a => a.F_EnCode == insuranceItem)
                                 .Select(a => new
                                 {
                                     fullname = a.F_FullName,
                                     coefficientperson = a.F_CoefficientPerson,
                                     coefficientcompany = a.F_CoefficientCompany
                                 }).ToList();
                                insurancesalary1 = insurance[0].Amount * insu[0].coefficientperson;
                                insurancesalary = insurancesalary + insurancesalary1;
                                insuranceitems = insuranceitems + insu[0].fullname + ":" + insurancesalary1 + ",";

                            }

                            //五险项目
                            salary.F_Insurance = insuranceitems;
                            salary.F_InsuranceSalary = insurancesalary;
                        }
                        else
                        {
                            salary.F_Insurance = "";
                            salary.F_InsuranceSalary = 0;

                        }
                    }
                    else
                    {
                        salary.F_Insurance = "";
                        salary.F_InsuranceSalary = 0;

                    }

                    //公积金
                    var providentitems = "";
                    float? providentsalary = 0;
                    float? providentsalary1 = 0;
                    if (insurance.Count > 0)
                    {
                        if (insurance[0].Providentitems.Count() > 0)
                        {
                            var providentItems = insurance[0].Providentitems.Split(",").ToList();


                            foreach (var providentItem in providentItems)
                            {
                                var insu = Db.Queryable<ProvidentitemsEntity>().Where(a => a.F_EnCode == providentItem)
                                 .Select(a => new
                                 {
                                     fullname = a.F_FullName,
                                     coefficientperson = a.F_CoefficientPerson,
                                     coefficientcompany = a.F_CoefficientCompany
                                 }).ToList();
                                providentsalary1 = insurance[0].Amount1 * insu[0].coefficientperson;
                                providentsalary = providentsalary + providentsalary1;
                                providentitems = providentitems + insu[0].fullname + ":" + providentsalary1 + ",";

                            }

                            salary.F_Provident = providentitems;
                            salary.F_ProvidentSalary = providentsalary;
                        }
                        else
                        {
                            salary.F_Provident = "";
                            salary.F_ProvidentSalary = 0;

                        }
                    }
                    else
                    {
                        salary.F_Provident = "";
                        salary.F_ProvidentSalary = 0;

                    }
                    //大病计提

                    salary.F_BigSickSalsry = _bigsickservice.GetAmountsick();

                    //计算请假

                    var holidaysname = "";


                    if (holidays.Count > 0)
                    {
                        foreach (var hoilday in holidays)
                        {
                            var type = Db.Queryable<HolidaytypeEntity>().Where(a => hoilday.F_Id == a.F_Id).Select(a => new HolidaytypeEntity() { F_Id = a.F_Id.SelectAll() }).ToList();
                            if (type.Count > 0)
                            {
                                holidaysname = holidaysname + type[0].F_FullName + ":" + hoilday.F_Days + ",";

                            }

                        }
                        salary.F_Holiday = holidaysname;

                    }


                    //计算奖惩

                    var awards = repository.Db.Queryable<ArewpunrecordsrecordsEntity>()
                        .GroupBy(a => a.F_ArewardsPunishmentsMark)
                     .Where(a => SqlFunc.DateDiff(DateType.Month, Convert.ToDateTime(a.F_HeadDate)
                     , time) == 0
                     && a.F_UserNum == item.UserNum && a.F_EnabledMark == true)

                   .Select((a) => new
                   {
                       arewardspunishment = a.F_ArewardsPunishmentsMark,
                       amount = SqlFunc.AggregateSum(a.F_Amount),


                   }).ToList();
                    if (awards.Count > 0)
                    {
                        foreach (var a in awards)
                        {
                            if (a.arewardspunishment == true)
                            {
                                salary.F_AwardSalary = a.amount;
                            }
                            else
                            {
                                salary.F_PunishmentSalary = a.amount;
                            }


                        }

                    }
                    else
                    {
                        salary.F_AwardSalary = 0;
                        salary.F_PunishmentSalary = 0;

                    }



                    //计算阶段奖
                    var yearendbonus = repository.Db.Queryable<YearendbonusitemEntity, YearendbonusEntity>((a, b) => new JoinQueryInfos(
                JoinType.Left, a.F_HeadId == b.F_Id
                ))
                    .GroupBy(a => a.F_UserNum)
                    .Where((a, b) => SqlFunc.DateDiff(DateType.Month, Convert.ToDateTime(b.F_HeadDate)
                    , time) == 0
                    && a.F_UserNum == item.UserNum)

                  .Select((a, b) => new
                  {

                      userid = a.F_UserNum,
                      amount = SqlFunc.AggregateSum(a.F_Amount)

                  }).ToList();


                    if (yearendbonus.Count > 0)
                    {
                        salary.F_YearEndBonusSalary = yearendbonus[0].amount;
                    }
                    else
                    {
                        salary.F_YearEndBonusSalary = 0;
                    }


                    //计算退税
                    var taxdeduc = repository.Db.Queryable<TaxdeductitemsEntity, TaxdeductEntity>((a, b) => new JoinQueryInfos(
                JoinType.Left, a.F_HeadId == b.F_Id
                ))
                    .GroupBy(a => a.F_UserNum)
                    .Where((a, b) => SqlFunc.DateDiff(DateType.Month, Convert.ToDateTime(b.F_HeadDate)
                    , time) == 0
                    && a.F_UserNum == item.UserNum)

                  .Select((a, b) => new
                  {

                      userid = a.F_UserNum,
                      amount = SqlFunc.AggregateSum(a.F_Amount)

                  }).ToList();

                    float? taxamount = 0;
                    if (taxdeduc.Count > 0)
                    {
                        taxamount = taxdeduc[0].amount;
                    }

                    //应得工资
                    salary.F_BasicSalary = salary.F_BasicSalary == null ? 0 : salary.F_BasicSalary;
                    salary.F_JopSalary = salary.F_JopSalary == null ? 0 : salary.F_JopSalary;
                    salary.F_SkillsSalary = salary.F_SkillsSalary == null ? 0 : salary.F_SkillsSalary;
                    salary.F_BenefitSalary = salary.F_BenefitSalary == null ? 0 : salary.F_BenefitSalary;
                    salary.F_ComAgeSalary = salary.F_ComAgeSalary == null ? 0 : salary.F_ComAgeSalary;
                    salary.F_TimesSalary = salary.F_TimesSalary == null ? 0 : salary.F_TimesSalary;
                    salary.F_NightShiftSalary = salary.F_NightShiftSalary == null ? 0 : salary.F_NightShiftSalary;
                    salary.F_WelfareSubsidySalary = salary.F_WelfareSubsidySalary == null ? 0 : salary.F_WelfareSubsidySalary;
                    salary.F_SubsidyAmount = salary.F_SubsidyAmount == null ? 0 : salary.F_SubsidyAmount;
                    salary.F_YearEndBonusSalary = salary.F_YearEndBonusSalary == null ? 0 : salary.F_YearEndBonusSalary;
                    salary.F_DeservedSalary = salary.F_DeservedSalary == null ? 0 : salary.F_DeservedSalary;
                    salary.F_InsuranceSalary = salary.F_InsuranceSalary == null ? 0 : salary.F_InsuranceSalary;
                    salary.F_ProvidentSalary = salary.F_ProvidentSalary == null ? 0 : salary.F_ProvidentSalary;
                    salary.F_BigSickSalsry = salary.F_BigSickSalsry == null ? 0 : salary.F_BigSickSalsry;
                    salary.F_PunishmentSalary = salary.F_PunishmentSalary == null ? 0 : salary.F_PunishmentSalary;

                    salary.F_DeservedSalary = salary.F_BasicSalary + salary.F_JopSalary + (float)salary.F_SkillsSalary + (float)salary.F_BenefitSalary + (float)salary.F_ComAgeSalary + (float)salary.F_TimesSalary + (float)salary.F_NightShiftSalary + salary.F_WelfareSubsidySalary + (float)salary.F_AwardSalary + (float)salary.F_SubsidyAmount;
                    //实得工资
                    salary.F_ReallySalary = salary.F_DeservedSalary - salary.F_InsuranceSalary - salary.F_ProvidentSalary - salary.F_BigSickSalsry - salary.F_PunishmentSalary;

                    //计算个税
                    float? reallytax = salary.F_ReallySalary + (float)salary.F_YearEndBonusSalary - taxamount;

                    var taxs = repository.Db.Queryable<PersontaxEntity>()

                  .Select((a) => new
                  {
                      upperlimit = a.F_Upperlimit,
                      lowerlimit = a.F_Lowerlimit,
                      coefficient = a.F_Coefficient,


                  }).ToList();
                    if (taxs.Count > 0)
                    {
                        foreach (var tax in taxs)
                        {
                            if (reallytax >= tax.lowerlimit && reallytax < tax.upperlimit)
                            {
                                salary.F_TaxSalary = reallytax * tax.coefficient;
                            }

                        }


                    }
                    else
                    {
                        salary.F_TaxSalary = 0;
                    }

                    //税后工资
                    salary.F_ReallySalary = salary.F_ReallySalary - salary.F_TaxSalary;
                    salary.BasicAmount = item.BasicAmount;
                    salary.JopAmount = item.JopAmount;
                    salary.BenefitCoefficient = item.BenefitCoefficient;
                    salary.SkillsAmount = item.SkillsAmount;
                    salary.F_JopName = item.JopName;
                }
                salary.F_UserId = item.UserId;
                salary.F_UserNum = item.UserNum;
                salary.F_RealName = item.RealName;

                salary.F_OrganizeId = Db.Queryable<OrganizeEntity>().Where(a => a.F_EnCode == item.orgid).ToList()[0].F_FullName;

                salarytableitemsList.Add(salary);

            }



            //查询考勤表按工号汇总工时、加班

            //权限过滤

            return salarytableitemsList;
        }

        public float Hoildaysum(List<HolidaytypeEntity> holidays, float? amount, float? workhours, Boolean isok = false)
        {

            float temp = 0;
            foreach (var hoilday in holidays)
            {
                var types = Db.Queryable<HolidaytypeEntity>().Where(a => hoilday.F_Id == a.F_Id).Select(a => new HolidaytypeEntity() { F_Id = a.F_Id.SelectAll() }).ToList();
                if (types.Count > 0)
                {
                    var type = types[0];
                    //计算请假天数减去容差天数
                    float? day = 0;
                    if (isok)
                    {
                        if (hoilday.F_Days >= type.F_Days)
                        {
                            temp = (float)(temp + (hoilday.F_Days - type.F_Days) * type.F_Percent * (amount / workhours) + type.F_Days * (amount / workhours));
                        }
                        else
                        {
                            temp = (float)(temp + type.F_Days * (amount / workhours));

                        }

                    }
                    else
                    {
                        temp = (float)(temp + day * type.F_Percent * (amount / workhours));
                    }


                }

            }
            return temp;
        }


        #region 提交数据
        public async Task SubmitForm(SalarytableEntity entity, string keyValue)
        {
            if (string.IsNullOrEmpty(keyValue))
            {
                //初始值添加
                entity.F_DeleteMark = false;
                entity.Create();

            }
            else
            {
                //此处需修改
                entity.Modify(keyValue);

            }

            var dataList = new List<SalarytableitemsEntity>();
            if (entity.list == null || entity.list.Count == 0)
            {
                throw new Exception("工资明细不能为空!");
            }
            foreach (var item in entity.list)
            {
                item.Create();

                item.F_CreatorTime = entity.F_CreatorTime;
                item.F_HeadId = entity.F_Id;

                item.F_DeleteMark = false;
                item.F_CreatorTime = DateTime.Now;


                if (string.IsNullOrEmpty(item.F_UserNum))
                {
                    throw new Exception("请输入工号");
                }

                dataList.Add(item);
                entity.list = dataList;
            }
            repository.Db.Ado.BeginTran();
            if (string.IsNullOrEmpty(keyValue))
            {
                //初始值添加

                await repository.Insert(entity);
            }
            else
            {
                //此处需修改

                await repository.Update(entity);
            }
            await repository.Db.Deleteable<SalarytableitemsEntity>().Where(a => a.F_HeadId == entity.F_Id).ExecuteCommandAsync();

            //插入记录
            await repository.Db.Insertable(dataList).ExecuteCommandAsync();
            repository.Db.Ado.CommitTran();
        }

        public async Task DeleteForm(string keyValue)
        {
            var ids = keyValue.Split(',');

            //删除表体
            await repository.Db.Deleteable<SalarytableitemsEntity>().Where(a => ids.Contains(a.F_HeadId)).ExecuteCommandAsync();
            //删除表头
            await repository.Delete(a => ids.Contains(a.F_Id.ToString()));
        }

        public async Task ReviewForm(string keyValue, bool b)
        {

            var ids = keyValue.Split(',');

            await repository.Update(a => ids.Contains(a.F_Id), a => new SalarytableEntity
            {
                F_EnabledMark = b,

            });

            await repository.Db.Updateable<SalarytableitemsEntity>().SetColumns(p => new SalarytableitemsEntity()
            {
                F_EnabledMark = b,



            }).Where(a => ids.Contains(a.F_HeadId)).ExecuteCommandAsync();
        }


        #endregion

    }
}
